package apk.yoursms.smslist;

import java.util.ArrayList;

import android.app.ActivityManager;
import android.app.Dialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.text.Html;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import apk.yoursms.R;
import apk.yoursms.TitleBar;
import apk.yoursms.YourSmsActivity;
import apk.yoursms.database.SmsDbHelper;
import apk.yoursms.greendroid.QuickAction;
import apk.yoursms.greendroid.QuickActionBar;
import apk.yoursms.greendroid.QuickActionWidget;
import apk.yoursms.greendroid.QuickActionWidget.OnQuickActionClickListener;
import apk.yoursms.settings.SourceSettings;
import apk.yoursms.settings.Statistics;
import apk.yoursms.views.Button;
import apk.yoursms.views.TextView;

import com.flurry.android.FlurryAgent;

@SuppressWarnings("deprecation")
public class SmsList extends TitleBar {

    public static final int SEND_SMS = 0;
    public static final int COPY_CLIPBOARD = 1;
    public static final int SHARE = 2;
    private ArrayList<String> messages = new ArrayList<String>();
    private QuickActionWidget mBar;
    private CharSequence mes;
    private final int EMPTY_DIALOG = 1;
    private final int EMPTY_DIALOG_DOWNLOAD = 2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	setContentView(R.layout.smslist);

	prepareQuickActionBar();

	Bundle child = getIntent().getExtras();
	TextView title = (TextView) findViewById(R.id.title);
	title.setText(child.getString("name_child"));

	SharedPreferences prefs = PreferenceManager
		.getDefaultSharedPreferences(this.getBaseContext());

	ArrayList<String> arraySites = SourceSettings.setSourcesite(prefs);
	ArrayList<String> allSites = new ArrayList<String>();
	final SmsListAdapter adapter = new SmsListAdapter(this,
		R.layout.list_item, messages, allSites);
	ListView lv = (ListView) findViewById(R.id.list);
	registerForContextMenu(lv);
	lv.setAdapter(adapter);

	for (String site : arraySites) {

	    Cursor cursor = getContentResolver().query(
		    Uri.parse("content://apk.yoursms.database.SmsProvider/"
			    + getString(R.string.tableName)),
		    null,
		    SmsDbHelper.GROUP + "=\"" + child.getString("name_child")
			    + "\" AND " + SmsDbHelper.SMS_SITE + "=\"" + site
			    + "\"", null, null);

	    cursor.moveToFirst();
	    if ((cursor.getCount() != 0) && (cursor.getString(2) != null)) {
		do {
		    String textForSite = cursor.getString(2);
		    int length = textForSite.split(":=:").length;
		    for (int i = 0; i < length - 1; i++) {
			String parseText = Html
				.fromHtml(textForSite.split(":=:")[i])
				.toString().replace("\\", "");

			if (parseText != "") {
			    allSites.add(site);
			    messages.add(parseText);
			}
		    }
		} while (cursor.moveToNext());
	    }
	    adapter.notifyDataSetChanged();
	    cursor.close();

	}

	if ((messages.isEmpty()) && isServiceRunning()) {
	    showDialog(EMPTY_DIALOG_DOWNLOAD);
	} else if (messages.isEmpty()) {
	    showDialog(EMPTY_DIALOG);
	}
    }

    public void onStart() {
	super.onStart();
	Statistics.setData("SmsList");
	FlurryAgent.onStartSession(this,
		getString(R.string.flurry_publisher_id));
    }

    public void onStop() {
	super.onStop();
	FlurryAgent.onEndSession(this);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
	    ContextMenuInfo menuInfo) {
	AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
	mes = messages.get(info.position);
	mBar.show(info.targetView);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	if (keyCode == KeyEvent.KEYCODE_BACK) {
	    finish();
	    YourSmsActivity.showRatingDialog();
	} else if (keyCode == KeyEvent.KEYCODE_HOME) {
	    Statistics.setData("SmsList Home Click");
	}
	return false;
    }

    private void prepareQuickActionBar() {
	mBar = new QuickActionBar(this);
	mBar.addQuickAction(new MyQuickAction(this,
		R.drawable.gd_action_bar_compose, R.string.gd_compose));
	mBar.addQuickAction(new MyQuickAction(this,
		R.drawable.gd_action_bar_export, R.string.gd_export));
	mBar.addQuickAction(new MyQuickAction(this,
		R.drawable.gd_action_bar_share, R.string.gd_share));

	mBar.setOnQuickActionClickListener(mActionListener);
    }

    private OnQuickActionClickListener mActionListener = new OnQuickActionClickListener() {
	public void onQuickActionClicked(QuickActionWidget widget, int position) {
	    switch (position) {
	    case SEND_SMS:
		Statistics.setData("Send Sms");
		try {
		    Intent sendIntent = new Intent(Intent.ACTION_VIEW);
		    sendIntent.setData(Uri.parse("sms:"));
		    sendIntent.putExtra("sms_body", mes.toString() + "\n---\n"
			    + getString(R.string.sms_footer));
		    startActivity(sendIntent);
		} catch (Exception e) {
		    Toast.makeText(SmsList.this, R.string.error,
			    Toast.LENGTH_LONG).show();
		}
		break;

	    case COPY_CLIPBOARD:
		Statistics.setData("Copy To Clipboard");
		ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		clipboard.setText(mes.toString() + "\n---\n"
			+ getString(R.string.sms_footer));
		Toast.makeText(SmsList.this, R.string.clipboard,
			Toast.LENGTH_LONG).show();
		break;

	    case SHARE:
		Statistics.setData("Share");
		final Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(android.content.Intent.EXTRA_TEXT,
			mes.toString() + "\n---\n"
				+ getString(R.string.sms_footer));
		try {
		    startActivity(Intent.createChooser(intent,
			    getString(R.string.share)));
		} catch (android.content.ActivityNotFoundException ex) {
		    Toast.makeText(SmsList.this, R.string.error,
			    Toast.LENGTH_LONG).show();
		}
		break;

	    default:
		break;
	    }
	}
    };

    private static class MyQuickAction extends QuickAction {

	private static final ColorFilter BLACK_CF = new LightingColorFilter(
		Color.BLACK, Color.BLACK);

	public MyQuickAction(Context ctx, int drawableId, int titleId) {
	    super(ctx, buildDrawable(ctx, drawableId), titleId);
	}

	private static Drawable buildDrawable(Context ctx, int drawableId) {
	    Drawable d = ctx.getResources().getDrawable(drawableId);
	    d.setColorFilter(BLACK_CF);
	    return d;
	}

    }

    public void onClick(View v) {
	mBar.show(v);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
	final Dialog dialog = new Dialog(SmsList.this);
	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	dialog.setContentView(R.layout.empty_smslist);

	dialog.setCancelable(true);
	Button button = (Button) dialog.findViewById(R.id.emptyBtnOk);
	button.setOnClickListener(new OnClickListener() {
	    public void onClick(View v) {
		dialog.cancel();
		finish();
	    }
	});

	switch (id) {
	case EMPTY_DIALOG:
	    TextView tv = (TextView) dialog.findViewById(R.id.emptyTextField);
	    tv.setText(this.getString(R.string.empty_smslist));
	    // dialog.setCancelable(true);
	    //
	    // Button button = (Button) dialog.findViewById(R.id.emptyBtnOk);
	    // button.setOnClickListener(new OnClickListener() {
	    // public void onClick(View v) {
	    // dialog.cancel();
	    // finish();
	    // }
	    // });
	    //
	    // dialog.show();
	    // return dialog;
	    break;

	case EMPTY_DIALOG_DOWNLOAD:
	    tv = (TextView) dialog.findViewById(R.id.emptyTextField);
	    tv.setText(this.getString(R.string.empty_smslist_download));
	    // dialog.setCancelable(true);
	    //
	    // button = (Button) dialog.findViewById(R.id.emptyBtnOk);
	    // button.setOnClickListener(new OnClickListener() {
	    // public void onClick(View v) {
	    // dialog.cancel();
	    // finish();
	    // }
	    // });
	    //
	    // dialog.show();
	    // return dialog;
	    break;
	}
	// return null;
	dialog.show();
	return dialog;
    }

    private boolean isServiceRunning() {
	ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	for (RunningServiceInfo service : manager
		.getRunningServices(Integer.MAX_VALUE)) {
	    if ("apk.yoursms.download.DownloadService".equals(service.service
		    .getClassName())) {
		return true;
	    }
	}
	return false;
    }
}
